package com.us.usws.support.uitls;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import net.iwsh.core.utils.IDGenerator;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * resource manager util
 * @author fengyong
 * 
 */
public class ResourceUtil {

	private static Logger logger = Logger.getLogger(ResourceUtil.class);

	private static Properties props = new Properties();
	private static String classPath;
	private static String appAbsolutePath;
	private static boolean isWindows;

	static {
		initialize();
	}

	public static void initialize() {
		String osType = System.getProperty("os.name");
		isWindows = osType == null || osType.toUpperCase().indexOf("WINDOWS") > -1;
		if (isWindows) {
			classPath = ResourceUtil.class.getResource("/").getPath();
			classPath = classPath.replace("file:", "");
			int pos = classPath.indexOf("/classes/");
			if (pos > -1)
				classPath = classPath.substring(1, pos + 9);
		} else {
			classPath = ResourceUtil.class.getResource("").getPath();
			classPath = classPath.replace("file:", "");
			int pos = classPath.indexOf("/classes/");
			if (pos == -1) {
				pos = classPath.indexOf("/lib/");
				if (pos > -1)
					classPath = classPath.substring(0, pos + 5);
			} else {
				classPath = classPath.substring(0, pos + 9);
			}
		}
		classPath = classPath.replaceAll("/lib/", "/classes/");

		appAbsolutePath = classPath.replaceAll("/WEB-INF/classes/", "");
		// appRoot =
		// appAbsolutePath.substring(appAbsolutePath.lastIndexOf("/"));
		try {
			classPath = java.net.URLDecoder.decode(classPath, "UTF-8");
		} catch (Exception e) {
			// do nothing
		}

		loadProperties(classPath + "application.properties");
	}

	private static void loadProperties(String propertyFile) {
		InputStream ins = null;
		try {
			ins = new FileInputStream(propertyFile);
			props.load(ins);
			ins.close();
		} catch (Exception e) {
			logger.error("Can't found system config file: " + propertyFile + ", please check." + e);
		} finally {
			try {
				if (ins != null)
					ins.close();
			} catch (IOException e) {
				// do nothing
			}
		}
	}

	public static String getAppAbsolutePath() {
		return appAbsolutePath;
	}

	/**
	 * upload file
	 * @param savePath
	 * @param type
	 * @param file
	 * @param fileName
	 * @return
	 */
	public static String uploadFile(String savePath, String type, File file, String fileName) {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;

		if (StringUtils.isNotBlank(fileName)) {
			fileName = IDGenerator.getInstance().genUID() + fileName.substring(fileName.lastIndexOf("."));
		}
		String descPath = savePath + "/local_upload/" + type;
		String filePath = descPath + "/" + fileName;
		File folder = new File(descPath);
		if (!folder.exists() && !folder.mkdirs()) {
			logger.error("dir not exist.and can not create the dir:" + descPath);
			return null;
		}
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(new FileOutputStream(filePath));
			byte[] buff = new byte[8192];
			int i;
			while ((i = bis.read(buff)) != -1)
				bos.write(buff, 0, i);
			bos.flush();

			return "/local_upload/" + type + "/" + fileName;
		} catch (IOException e) {
			logger.error("Save file failed: " + e);
			return null;
		} finally {
			try {
				if (bos != null)
					bos.close();
				if (bis != null)
					bis.close();
			} catch (IOException e) {
				// do nothing
			}
		}
	}

	/**
	 * delete file by the path
	 *@param sPath  
	 *@return 
	 */
	public static boolean deleteFolder(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		if (!file.exists()) {
			return flag;
		} else {
			if (file.isFile()) {
				return deleteFile(sPath);
			} else {
				return deleteDirectory(sPath);
			}
		}
	}

	/**
	 * @param   sPath    
	 * @return
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);

		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	/**
	 * @param  
	 * @return
	 */
	public static boolean deleteDirectory(String sPath) {

		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);

		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;

		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean urlExists(String URLName) {
		HttpURLConnection.setFollowRedirects(false);
		HttpURLConnection con = null;
		try {
			URL url = new URL(URLName);

			con = (HttpURLConnection) url.openConnection();

			con.setRequestMethod("HEAD");

			return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static String getProperty(String key, String defaultProperty) {
		return props.getProperty(key, defaultProperty);
	}

	public static String getProperty(String key) {
		return props.getProperty(key);
	}
}
